﻿#include "function_frank_width.h"
#include "para.h"

extern MyPARA my_para;
// Procedures
void frankWidth (HObject ho_image, HObject *ho_region_show, HTuple hv_row1, HTuple hv_column1,
    HTuple hv_row2, HTuple hv_column2, HTuple *hv_ret, HTuple *hv_detection_column1,
    HTuple *hv_detection_column2)
{

  // Local iconic variables
  HObject  ho_Rectangle, ho_ImageReduced, ho_Region;
  HObject  ho_RegionFillUp, ho_ConnectedRegions, ho_SelectedRegions;

  // Local control variables
  HTuple  hv_UsedThreshold, hv_Number, hv_DetectionRow1;
  HTuple  hv_DetectionRow2;

  GenRectangle1(&ho_Rectangle, hv_row1, hv_column1, hv_row2, hv_column2);
  ReduceDomain(ho_image, ho_Rectangle, &ho_ImageReduced);
  BinaryThreshold(ho_ImageReduced, &ho_Region, "max_separability", "dark", &hv_UsedThreshold);
  FillUp(ho_Region, &ho_RegionFillUp);
  Connection(ho_RegionFillUp, &ho_ConnectedRegions);
  CountObj(ho_ConnectedRegions, &hv_Number);
  if (0 != (int(hv_Number==0)))
  {
    (*hv_ret) = 0;
    return;
  }
  SelectShapeStd(ho_ConnectedRegions, &ho_SelectedRegions, "max_area", 70);
  SmallestRectangle1(ho_SelectedRegions, &hv_DetectionRow1, &(*hv_detection_column1),
      &hv_DetectionRow2, &(*hv_detection_column2));
  GenRectangle1(&(*ho_region_show), hv_DetectionRow1, (*hv_detection_column1), hv_DetectionRow2,
      (*hv_detection_column2));
  (*hv_ret) = 1;

}

FunctionFrankWidth::FunctionFrankWidth(QDialog* parent, QSettings* qsettings, QString section) : QDialog(parent)
{
	QSettings* m_settings_para = new QSettings(QCoreApplication::applicationDirPath() +"/para" +"/para.ini", QSettings::IniFormat);
	m_settings_para->setIniCodec("UTF-8");
	m_save_image_dir = m_settings_para->value("para/m_save_image_dir", "").toString();


    m_qsettings = qsettings;
    m_section = section;

    this->setWindowTitle(("Frank Width"));
    QRect desktop_rect = QApplication::desktop()->geometry();
    double ratio_x = desktop_rect.width()/1920.0;
    double ratio_y = desktop_rect.height()/1080.0;

    move(0,0);
    setFixedSize(1920*ratio_x,1010*ratio_y);



    m_view = new MyQGraphicsView(this);
    m_view->setGeometry(660 * ratio_x, 0, 1250 * ratio_x, 940 * ratio_y);

    m_view->m_graphics_shape_rect = new GraphicsShapeRect(100, 100, 100, 100,Qt::blue);
    m_view->m_graphics_shape_rect->setFlag(QGraphicsItem::ItemIsMovable, false); // 明确禁用移动

    m_view->m_graphics_shape_rect->setFlag(QGraphicsItem::ItemIsSelectable, false); // 保留选择功能

    m_view->m_scene->addItem(m_view->m_graphics_shape_rect);
    QRectF qrectf = m_view->m_graphics_shape_rect->boundingRect();
    connect(m_view->m_graphics_shape_rect, &GraphicsShapeRect::sendMessage, m_view->m_pixmapItem, &MyQGraphicsPixmapItem::receiveMessage);

    row1 = (int)qrectf.y();
    column1 = (int)qrectf.x();
    row2 = (int)(qrectf.y() + qrectf.height());
    column2 = (int)(qrectf.x() + qrectf.width());
    

    QSize control_size(220*ratio_x,40*ratio_y);

    QWidget* p = new QWidget(this);
    p->move(0*ratio_x,0*ratio_y);
    p->setFixedSize(600*ratio_x,800*ratio_y);

    QGridLayout *qgridLayout = new QGridLayout();
    p->setLayout(qgridLayout);

    int index = 0;

    QSize ButtonSize(220 * ratio_x, 40 * ratio_y);

    m_qlabel_row1->setText("Top");
    m_qlabel_row1->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_row1, index, 0);

    m_qpinbox_row1->setFixedSize(control_size);
    m_qpinbox_row1->setMinimum(0);
    m_qpinbox_row1->setMaximum(100000);
    qgridLayout->addWidget(m_qpinbox_row1, index, 1);
    index++;

    m_qlabel_column1->setText("Left");
    m_qlabel_column1->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_column1, index, 0);
    m_qpinbox_column1->setFixedSize(control_size);
    m_qpinbox_column1->setMinimum(0);
    m_qpinbox_column1->setMaximum(100000);
    qgridLayout->addWidget(m_qpinbox_column1, index, 1);
    index++;

    m_qlabel_row2->setText("Bottom");
    m_qlabel_row2->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_row2, index, 0);
    m_qpinbox_row2->setFixedSize(control_size);
    m_qpinbox_row2->setMinimum(0);
    m_qpinbox_row2->setMaximum(100000);
    qgridLayout->addWidget(m_qpinbox_row2, index, 1);
    index++;

    m_qlabel_column2->setText("Right");
    m_qlabel_column2->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_column2, index, 0);
    m_qpinbox_column2->setFixedSize(control_size);
    m_qpinbox_column2->setMinimum(0);
    m_qpinbox_column2->setMaximum(100000);
    qgridLayout->addWidget(m_qpinbox_column2, index, 1);
    index++;

    m_qlabel_width_min = new QLabel();
    m_qlabel_width_min->setText("Min");
    m_qlabel_width_min->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_width_min, index, 0);
    m_qspinbox_width_min = new QSpinBox();
    m_qspinbox_width_min->setFixedSize(control_size);
    m_qspinbox_width_min->setMinimum(1);
    m_qspinbox_width_min->setMaximum(10000);
    qgridLayout->addWidget(m_qspinbox_width_min, index, 1);
    index++;
    m_qlabel_width_max = new QLabel();
    m_qlabel_width_max->setText("Max");
    m_qlabel_width_max->setFixedSize(control_size);
    qgridLayout->addWidget(m_qlabel_width_max, index, 0);
    m_qspinbox_width_max = new QSpinBox();
    m_qspinbox_width_max->setFixedSize(control_size);
    m_qspinbox_width_max->setMinimum(1);
    m_qspinbox_width_max->setMaximum(10000);
    qgridLayout->addWidget(m_qspinbox_width_max, index, 1);
    index++;



    m_pushbutton_save_parameter = new QPushButton(this);
    m_pushbutton_save_parameter->setFixedSize(control_size);
    m_pushbutton_save_parameter->setText("Save");
    connect(m_pushbutton_save_parameter, &QPushButton::clicked, this, &FunctionFrankWidth::saveParameter);
    qgridLayout->addWidget(m_pushbutton_save_parameter, index,0);
    index++;

    m_pushbutton_show_orign_image = new QPushButton(this);
    m_pushbutton_show_orign_image->setFixedSize(control_size);
    m_pushbutton_show_orign_image->setText("ShowOrign");
    connect(m_pushbutton_show_orign_image, &QPushButton::clicked, this,[=]() {
        QImage q_image = matToQImage(m_image);
        m_view->setImage(q_image,"");
        return true;
    });
    qgridLayout->addWidget(m_pushbutton_show_orign_image, index,0);

    m_pushbutton_detection = new QPushButton(this);
    m_pushbutton_detection->setFixedSize(control_size);
    m_pushbutton_detection->setText("Detection");
    connect(m_pushbutton_detection, &QPushButton::clicked, this, &FunctionFrankWidth::detectionImage);
    qgridLayout->addWidget(m_pushbutton_detection, index,1);
    index++;

    m_pushbutton_return = new QPushButton(this);
    m_pushbutton_return->setFixedSize(control_size);
    m_pushbutton_return->setText("Exit");
    qgridLayout->addWidget(m_pushbutton_return, index, 0);
    connect(m_pushbutton_return, &QPushButton::clicked, this, [=]() {
        this->hide();
        });
	index++;
    


    loadParameter();

}

FunctionFrankWidth::~FunctionFrankWidth()
{
    ;
}


int FunctionFrankWidth::detection(HObject image, QString& message)
{
    try
    {
        HTuple hv_detection_column1,hv_detection_column2, hv_ret;


       frankWidth(image,&m_hobject_show, row1, column1, row2, column2,&hv_ret,&hv_detection_column1,&hv_detection_column2);



        int ret = hv_ret[0].I();

        if(ret<1)
        {
            return true;
            message = "frank error empty ";
            return false;
        }
        int  detection_column1 = hv_detection_column1[0].I();
        int  detection_column2 = hv_detection_column2[0].I();


            if(detection_column1==column1)
            {
                message = "frank error left exceed﻿";
                return false;
            }
            if(detection_column2==column2)
            {
                message = "frank error right exceed﻿";
                return false;
            }


        int width = detection_column2- detection_column1;


        if(width>m_width_max)
        {
            message = "frank error" + QString::number(width);
            return false;
        }
        if(width<m_width_min)
        {
            message = "frank error" +QString::number(width);
            return false;
        }
		else
		{
			message = "frank width" + QString::number(width);
			return true;
		}

    }
    catch (HException &HDevExpDefaultException)
    {
        message = HDevExpDefaultException.ErrorMessage();
        return false;
    }


    return 1;

}

void FunctionFrankWidth::detectionImage()
{
    if(m_image.empty())
       {
           QMessageBox::information(nullptr,"","nop image");
           return;
       }

       QString message;


       HObject image = matToHImage(m_image);

       bool state = detection(image, message);

       if(state)
       {
           message += "OK";
       }

       Mat image_show;

       draw(m_image,image_show);

       QImage q_image = matToQImage(image_show);
       if (!q_image.isNull())
       {
           m_view->setImage(q_image, message);
       }

}

void FunctionFrankWidth::draw(Mat image_in, Mat& image_out)
{
	image_out = image_in.clone();
	if (image_out.channels() == 1)
	{
		cvtColor(image_out, image_out, COLOR_GRAY2BGR);
	}
	image_out = drawRegion(image_out,m_hobject_show, Scalar(0, 255, 0));
    GenEmptyRegion(&m_hobject_show);

}

void FunctionFrankWidth::loadParameter()
{
    try
    {
        row1 = m_qsettings->value(m_section + "/" + "Row1",100).toInt();
        column1 = m_qsettings->value(m_section + "/" + "Column1",100).toInt();
        row2 = m_qsettings->value(m_section + "/" + "Row2",200).toInt();
        column2 = m_qsettings->value(m_section + "/" + "Column2",200).toInt();

        m_qpinbox_row1->setValue(row1);
        m_qpinbox_column1->setValue(column1);
        m_qpinbox_row2->setValue(row2);
        m_qpinbox_column2->setValue(column2);

        m_view->setRectPose(row1, column1, row2, column2);

        m_width_min = m_qsettings->value(m_section + "/" + "m_width_min").toInt();
        m_width_max = m_qsettings->value(m_section + "/" + "m_width_max").toInt();
        m_qspinbox_width_min->setValue(m_width_min);
        m_qspinbox_width_max->setValue(m_width_max);

    }
    catch(exception& error)
    {
        QMessageBox::critical(nullptr,error.what() , m_section + "para error");
    }
    return ;
}

void FunctionFrankWidth::saveParameter()
{
    try
        {

			

            m_width_min = m_qspinbox_width_min->value();
            m_width_max = m_qspinbox_width_max->value();

            row1 = m_qpinbox_row1->value();
            column1 = m_qpinbox_column1->value();
            row2 = m_qpinbox_row2->value();
            column2 = m_qpinbox_column2->value();

            m_view->setRectPose(row1, column1, row2, column2);


			if (my_para.m_login_privilege >= 2)
			{



                    m_qsettings->setValue(m_section + "/" + "Row1", row1);
                    m_qsettings->setValue(m_section + "/" + "Column1", column1);
                    m_qsettings->setValue(m_section + "/" + "Row2", row2);
                    m_qsettings->setValue(m_section + "/" + "Column2", column2);



				m_qsettings->setValue(m_section + "/" + "m_width_min", m_width_min);
				m_qsettings->setValue(m_section + "/" + "m_width_max", m_width_max);
			}




        }
        catch(exception& error)
        {
            QMessageBox::critical(nullptr,error.what() , m_section + "para error");
        }
    


}

bool FunctionFrankWidth::showDialog()
{
    QImage q_image = matToQImage(m_image);
    m_view->setImage(q_image,"");
    return true;
}



